//增删改查
const Company = require("../models/companyModel");

exports.createCompany = async (req, res) => {
  try {
    const newCompany = await Company.create(req.body);
    res.status(201).json({
      status: "success",
      data: newCompany,
    });
  } catch (err) {
    // console.log(req.body);
    res.status(404).json({
      message: err,
    });
  }
};

exports.deleteCompany = async (req, res) => {
  try {
    await Company.deleteMany({ _id: req.body._id }, (err, data) => {
      if (err) {
        res.status(409).json({
          status: true,
          message: err,
        });
      }
      res.status(200).json({
        status: true,
        message: "删除成功",
      });
    });
  } catch (err) {
    console.log(err);
  }
};

exports.updateCompany = async (req, res) => {
  try {
    const newdata = await Company.updateOne({ _id: req.body._id }, req.body);
    // console.log(req.body);
    res.status(200).json({
      status: true,
      message: "success",
      newdata: newdata,
    });
  } catch (err) {
    console.log(err);
    res.status(404).json({
      err,
    });
  }
};

exports.getAllcompany = async (req, res) => {
  try {
    const company = await Company.find();
    res.status(200).json({
      status: true,
      message: company,
    });
  } catch (err) {
    console.log(err);
  }
};

//通过用户的company_id找到公司相关信息
exports.getCompanyInfoById = async (req, res) => {
  try {
    if (req.user.company_id) {
      const companyInfo = await Company.findOne({ _id: req.user.company_id });
      res.status(200).json({
        status: "success",
        message: companyInfo,
      });
    } else {
      res.status(404).json({
        status: "fail",
        message: "The employee does not have a company ID",
      });
    }
  } catch (err) {
    res.status(404).json({
      Error: err,
    });
  }
};

//通过用户公司id更新用户信息(会验证token,管理员只能修改它自己公司的部分信息)
exports.updateCompanyInfoById = async (req, res) => {
  try {
    if (req.user.company_id) {
      const companyInfo = await Company.findByIdAndUpdate(
        req.user.company_id,
        req.body,
        {
          new: true,
        }
      );
      res.status(200).json({
        status: "success",
        companyInfo: companyInfo,
      });
    } else {
      res.status(404).json({
        status: "fail",
        message: "The employee does not have a company ID",
      });
    }
  } catch (err) {
    console.log(err);
    res.status(404).json({
      err,
    });
  }
};
